package com.xiaocikuai.smallchunks.service.Pay;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.wechat.pay.java.service.transferbatch.TransferBatchService;
import com.wechat.pay.java.service.transferbatch.model.InitiateBatchTransferRequest;
import com.wechat.pay.java.service.transferbatch.model.InitiateBatchTransferResponse;
import com.xiaocikuai.smallchunks.config.WxPayAppConfig;
import com.xiaocikuai.smallchunks.entity.User.MemberSale;



/*
import com.wechat.pay.java.service.refund.RefundServiceExtension;
import com.wechat.pay.java.service.refund.model.CreateRefundRequest;
import com.wechat.pay.java.service.refund.model.CreateRefundResponse;
*/

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;


import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class WX_PayServiceImpl implements WxPayService {

    @Override
    public Map<String, String> nativePayV3(String out_trade_no, String money) {

        Config config = new RSAAutoCertificateConfig.Builder()
                .merchantId(WxPayAppConfig.mchId)
                .privateKeyFromPath(WxPayAppConfig.privateKeyPath)
                .merchantSerialNumber(WxPayAppConfig.merchantSerialNumber)
                .apiV3Key(WxPayAppConfig.apiV3key)
                .build();

        NativePayService service = new NativePayService.Builder().config(config).build();

        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        // 将金额转换为分
        amount.setTotal((int) (Double.parseDouble(money)));
        request.setAmount(amount);
        request.setAppid(WxPayAppConfig.appId);
        request.setMchid(WxPayAppConfig.mchId);
        request.setDescription("测试商品");
        request.setNotifyUrl(WxPayAppConfig.notifyUrl);
        request.setOutTradeNo(out_trade_no);
        PrepayResponse response = service.prepay(request);
        Map<String, String> payParameters = new HashMap<>();
//        System.out.println("Payment URL: " + response);
        payParameters.put("code_url", response.getCodeUrl());
//        System.out.println("Payment URL: " + response.getCodeUrl());
        return payParameters;

    }

    @Override
    public Map<String, String> jsapiPayV3(String out_trade_no, String money, String openID) {

        Config config = new RSAAutoCertificateConfig.Builder()
                .merchantId(WxPayAppConfig.mchId)
                .privateKeyFromPath(WxPayAppConfig.privateKeyPath)
                .merchantSerialNumber(WxPayAppConfig.merchantSerialNumber)
                .apiV3Key(WxPayAppConfig.apiV3key)
                .build();

        com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension jsapiService = new JsapiServiceExtension.Builder().config(config).build();

        com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest request = new com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest();

        com.wechat.pay.java.service.payments.jsapi.model.Amount amount = new com.wechat.pay.java.service.payments.jsapi.model.Amount();
        // 将金额转换为分
        amount.setTotal((int) (Double.parseDouble(money)));
        request.setAmount(amount);
        request.setAppid(WxPayAppConfig.appId);
        request.setMchid(WxPayAppConfig.mchId);
        Payer payer = new Payer();
        payer.setOpenid(openID);
        request.setPayer(payer);
        request.setDescription("测试商品");
        request.setNotifyUrl(WxPayAppConfig.notifyUrl);
        request.setOutTradeNo(out_trade_no);

        PrepayWithRequestPaymentResponse response = jsapiService.prepayWithRequestPayment(request);

        Map<String, String> payParameters = new HashMap<>();
        payParameters.put("timestamp", response.getTimeStamp());
        payParameters.put("packageVal", response.getPackageVal());
        payParameters.put("nonceStr", response.getNonceStr());
        payParameters.put("signType", response.getSignType());
        payParameters.put("paySign", response.getPaySign());
        return payParameters;

    }






//    public Map<String, String> jsapiRefundV3(String out_trade_no, String refundMoney, String reason) {
//
//        // 构建配置
//        RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
//                .merchantId(WxPayAppConfig.mchId)
//                .privateKeyFromPath(WxPayAppConfig.privateKeyPath)
//                .merchantSerialNumber(WxPayAppConfig.merchantSerialNumber)
//                .apiV3Key(WxPayAppConfig.apiV3key)
//                .build();
//
//      // 创建退款服务扩展对象
//        RefundService refundService = new RefundService.Builder().config(config).build();
//
//        // 创建退款请求对象
//        CreateRefundRequest refundRequest = new CreateRefundRequest();
//        refundRequest.setOutTradeNo(out_trade_no);
//        // 将退款金额转换为分
//        refundRequest.setRefundAmount((int) (Double.parseDouble(refundMoney)));
//        refundRequest.setRefundReason(reason);
//
//        // 发起退款请求
//        CreateRefundResponse refundResponse = refundService.createRefund(refundRequest);
//
//        Map<String, String> refundParameters = new HashMap<>();
//        refundParameters.put("refundId", refundResponse.getRefundId());
//        refundParameters.put("refundStatus", refundResponse.getRefundStatus());
//        return refundParameters;
//    }


    public Map<String, String> MemberSale(List<MemberSale> memberSales, Long totalAmount) {
        Config config = new RSAAutoCertificateConfig.Builder()
                .merchantId(WxPayAppConfig.mchId)
                .privateKeyFromPath(WxPayAppConfig.privateKeyPath)
                .merchantSerialNumber(WxPayAppConfig.merchantSerialNumber)
                .apiV3Key(WxPayAppConfig.apiV3key)
                .build();
        TransferBatchService service = new TransferBatchService.Builder().config(config).build();
        InitiateBatchTransferRequest initiateBatchTransferRequest = new InitiateBatchTransferRequest();


        initiateBatchTransferRequest.setAppid("");
        initiateBatchTransferRequest.setOutBatchNo("");
        initiateBatchTransferRequest.setBatchName("");
        initiateBatchTransferRequest.setBatchRemark("");
        initiateBatchTransferRequest.setTotalAmount(totalAmount);
        initiateBatchTransferRequest.setTotalNum(memberSales.size());
        {
            List<com.wechat.pay.java.service.transferbatch.model.TransferDetailInput> transferDetailListList = new ArrayList<>();
            for (MemberSale memberSale:memberSales){
                com.wechat.pay.java.service.transferbatch.model.TransferDetailInput transferDetailInput = new com.wechat.pay.java.service.transferbatch.model.TransferDetailInput();
                transferDetailInput.setOutDetailNo(String.valueOf(memberSale.getId()));//【商家明细单号】 商户系统内部区分转账批次单下不同转账明细单的唯一标识，要求此参数只能由数字、大小写字母组成
                transferDetailInput.setTransferAmount((long) (memberSale.getMoney() * -1));
                transferDetailInput.setTransferRemark("小词块分销提现");//【转账备注】 单条转账备注（微信用户会收到该备注），UTF8编码，最多允许32个字符
                transferDetailInput.setOpenid(memberSale.getOpenId());
                transferDetailInput.setUserName(null);
                /*【收款用户姓名】 收款方真实姓名。支持标准RSA算法和国密算法，公钥由微信侧提供
                明细转账金额<0.3元时，不允许填写收款用户姓名
                明细转账金额 >= 2,000元时，该笔明细必须填写收款用户姓名
                同一批次转账明细中的姓名字段传入规则需保持一致，也即全部填写、或全部不填写
                若商户传入收款用户姓名，微信支付会校验用户openID与姓名是否一致，并提供电子回单*/
                transferDetailListList.add(transferDetailInput);
            }
            initiateBatchTransferRequest.setTransferDetailList(transferDetailListList);
        }
        initiateBatchTransferRequest.setTransferSceneId("1000");//【转账场景ID】 该批次转账使用的转账场景，如不填写则使用商家的默认场景，如无默认场景可为空，可前往“商家转账到零钱-前往功能”中申请。
//        initiateBatchTransferRequest.setNotifyUrl("https://www.weixin.qq.com/wxpay/pay.php");
        //【通知地址】 异步接收微信支付结果通知的回调地址，通知url必须为公网可访问的url，必须为https，不能携带参数。
        InitiateBatchTransferResponse response = service.initiateBatchTransfer(initiateBatchTransferRequest);

        Map<String, String> payParameters = new HashMap<>();
        payParameters.put("out_batch_no", response.getOutBatchNo());
        payParameters.put("batch_id", response.getBatchId());
        payParameters.put("create_time", response.getCreateTime());
        payParameters.put("batch_status", response.getBatchStatus());
        return payParameters;


    }



}




